package com.zhanghp.class006;

import java.util.Arrays;

import static com.zhanghp.common.ArrUtil.*;
/**
 * @author zhanghp
 * @since 2024/3/5 10:55
 */
// 有序数组中找>=num的最左位置
public class Code02_FindLeft {

    public static void main(String[] args) {
        validator(1_000, 10, 100, arr -> {
            Arrays.sort(arr);
            int num = (int)(Math.random() * 100) + 1;
            if (right(arr, num) != findLeft(arr, num)) {
                System.out.println("出错了！");
            }
        });
    }

    public static int right(int[] arr, int num){
        int ans = -1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] >= num) {
                ans = i;
                break;
            }
        }
        return ans;
    }

    public static int findLeft(int[] arr, int num) {
        if (arr == null || arr.length == 0) {
            return -1;
        }
        int l = 0, mid = 0, r = arr.length - 1, ans = -1;
        while (l <= r) {
            mid = l + ((r - l) >> 1);
            if (arr[mid] >= num) {
                ans = mid;
                r = mid - 1;
            }else {
                l = mid + 1;
            }
        }
        return ans;
    }
}
